package tgc.edu.demo.jkxt.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import tgc.edu.demo.jkxt.entity.SysRole;
import tgc.edu.demo.jkxt.entity.SysUser;
import tgc.edu.demo.jkxt.repository.SysUserRepository;

@Component
public class UserUtils {
	@Autowired
	private SysUserRepository userDAO;
	
	public SysUser getUser() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username=userDetails.getUsername();
		SysUser user=userDAO.findByUsername(username);
		return user;
	}
	
	public boolean hasRole(String role) {
		List<SysRole> roles=getUser().getRoles();
		List<String> roleNames=new ArrayList<>();
		for (SysRole sysRole : roles) {
			roleNames.add(sysRole.getName());
		}
		return roleNames.contains(role);
	}
	
	public String getName() {
		User2 user2= (User2)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		return user2.getName();
	}
	public String getUsername() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username=userDetails.getUsername();
		return username;
	}
	
	public String getRoles() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String roles = userDetails.getAuthorities().toString();
		return roles.substring(1,roles.length()-1);
	}
}
